package com.qfedu.common.core.utils;




import com.qfedu.common.core.constant.CommonConstant;
import com.qfedu.common.core.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import reactor.core.publisher.Mono;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author zsjx
 * 2024/12/26 下午4:39
 * com.qfedu.core.utils
 * micro2405
 */

//@Component
public class TokenUtils {

    private static final Logger log = LoggerFactory.getLogger(TokenUtils.class);

    public static Integer getUserId() {

        // 动态获取HttpServletRequest对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();

        // token: null
        String token = request.getHeader(CommonConstant.TOKEN);
        log.info("获取到的token为：{}", token);

/*
        // 使用redis中获取用户信息
        RedisUtil redisUtil = SpringBeanUtils.getBean(RedisUtil.class);
//        User user = redisUtil.getCacheObject(String.format(RedisKeyEnum.KEY_LOGIN.getKey(), token) + token);
        User user = redisUtil.getCacheObject("token:" + token);
        return user.getId();*/

        // 使用JWT获取用户信息
        Claims claims = JwtUtils.parseJWT(token);
        return (Integer) claims.get("userId");
    }

    /**
     * 从请求中获取用户ID
     * @param token 请求中的token
     * @return 用户ID
     */
    public static Mono<Integer> getUserIdFromRequest(String token) {
        if (token == null) {
            return Mono.error(new RuntimeException("No Token available"));
        }

        return Mono.justOrEmpty(JwtUtils.parseJWT(token).get("userId", Integer.class));
    }

}
